package com.sun.thread;

import java.util.concurrent.Exchanger;

public class ExchangerDemo {

    public static void main(String[] args) {
        // 理解成交换物资区域
        Exchanger<String> exchanger = new Exchanger<>();

        new Thread(() -> {
            String msgA = "消息A~~~";
            try {
                Thread.sleep(3000);
                String exchange = exchanger.exchange(msgA);
                System.out.println(Thread.currentThread().getName() + "已发送消息:" + msgA + "接收到消息：" + exchange);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }, "线程A").start();

        new Thread(() -> {
            String msgA = "消息B~~~";
            try {
                String exchange = exchanger.exchange(msgA);
                System.out.println(Thread.currentThread().getName() + "已发送消息:" + msgA + "接收到消息：" + exchange);
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }, "线程B").start();
    }
}
